package com.kaguya.vams.security.handler;

import cn.hutool.json.JSONUtil;
import com.kaguya.vams.domain.Result;
import com.kaguya.vams.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;
import org.springframework.security.web.authentication.logout.SecurityContextLogoutHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.ws.Action;
import java.io.IOException;

/**
 * 登录退出成功处理器
 *
 * @author : kaguya
 * @date : 20:18 2021/8/2
 */
@Slf4j
@Component
public class JwtLogoutSuccessHandler implements LogoutSuccessHandler {

    @Autowired
    JwtUtils jwtUtils;

    @Override
    public void onLogoutSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException, ServletException {

        log.info("-退出成功");
        //清空jwt
        if (authentication != null) {
            new SecurityContextLogoutHandler().logout(httpServletRequest, httpServletResponse, authentication);
        }
        httpServletResponse.setContentType("application/json;charset=UTF-8");
        httpServletResponse.setHeader(jwtUtils.getHeader(), "");

        ServletOutputStream out = httpServletResponse.getOutputStream();
        out.write(JSONUtil.toJsonStr(Result.ok()).getBytes("UTF-8"));
        out.flush();
        out.close();
    }
}
